package com.jswdwsx.esign.config

import com.jswdwsx.esign.protocol.EsignApi
import com.jswdwsx.esign.protocol.EsignCallAdapterFactory
import com.jswdwsx.esign.protocol.EsignTokenInterceptor
import com.jswdwsx.esign.service.StoredTokenService
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

@Configuration
class EsignApiConfig(
    private val esignProperties: EsignProperties,
    private val storedTokenService: StoredTokenService
) {

    @Bean
    fun identityTokenInterceptor(): Interceptor {
        return EsignTokenInterceptor(
            esignProperties.identity,
            storedTokenService
        )
    }

    @Bean
    fun nonIdentityTokenInterceptor(): Interceptor {
        return EsignTokenInterceptor(
            esignProperties.nonIdentity,
            storedTokenService
        )
    }

    @Bean
    fun esignIdentityHttpClient(identityTokenInterceptor: Interceptor): OkHttpClient {
        return createOkHttpClient(identityTokenInterceptor)
    }

    @Bean
    fun esignNonIdentityHttpClient(nonIdentityTokenInterceptor: Interceptor): OkHttpClient {
        return createOkHttpClient(nonIdentityTokenInterceptor)
    }

    private fun createOkHttpClient(interceptor: Interceptor): OkHttpClient {
        return OkHttpClient.Builder()
            .addInterceptor(interceptor)
            .readTimeout(100, TimeUnit.SECONDS)
            .retryOnConnectionFailure(true)
            .build()
    }


    @Bean
    fun esignApi(@Autowired @Qualifier("esignNonIdentityHttpClient") esignNonIdentityHttpClient: OkHttpClient): EsignApi? {
        val retrofit = Retrofit.Builder().baseUrl(esignProperties.host)
            .client(esignNonIdentityHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(EsignCallAdapterFactory.create())
            .build()
        return retrofit.create(EsignApi::class.java)
    }

    @Bean
    fun esignApiWithIdentity(@Autowired @Qualifier("esignIdentityHttpClient") esignIdentityHttpClient: OkHttpClient): EsignApi? {
        val retrofit = Retrofit.Builder().baseUrl(esignProperties.host)
            .client(esignIdentityHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(EsignCallAdapterFactory.create())
            .build()
        return retrofit.create(EsignApi::class.java)
    }
}
